package com.xinsoft.controller.purchase;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xinsoft.common.Response;
import com.xinsoft.constant.Const;
import com.xinsoft.entity.dto.ScmPurchaseDto;
import com.xinsoft.entity.dto.ScmPurchaseNoticePageParam;
import com.xinsoft.entity.dto.ScmPurchasePageParam;
import com.xinsoft.entity.po.ScmPurchaseNotice;
import com.xinsoft.entity.po.ScmPurchaseNoticeItem;
import com.xinsoft.entity.po.ScmPurchasePlan;
import com.xinsoft.entity.vo.ScmPurchaseNoticePageVo;
import com.xinsoft.entity.vo.ScmPurchasePageVo;
import com.xinsoft.service.*;
import com.xinsoft.utils.ExcelUtils;
import com.xinsoft.utils.TokenUtil;
import com.xinsoft.validator.ValidatorUtils;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 收料通知
 */
@RestController
@RequestMapping("/scm/purchaseNotice")
public class ScmPurchaseNoticeController {

    @Autowired
    private ScmPurchaseNoticeService scmPurchaseNoticeService;
    @Autowired
    private ScmPurchaseNoticeItemService scmPurchaseNoticeItemService;
    @Autowired
    private SysDocumentNumService sysDocumentNumService;


    /**
     * 保存收料通知
     */
    @PostMapping("/addOrUpdate")
    @Transactional(rollbackFor = Exception.class)
    public Response<?> addOrUpdate(@RequestBody ScmPurchaseNotice scmPurchaseDto) {
        // 参数校验
        if (ObjectUtil.isNotEmpty(scmPurchaseDto.getId())){
            ScmPurchaseNotice noticeDO = scmPurchaseNoticeService.getById(scmPurchaseDto.getId());
            if (noticeDO.getAuditStatus().equals(Const.AUDIT_STATUS_NORMAL)){
                Response.fail("该单据已被审核，不能编辑！");
            }
        }
        // 更新计划单号
        sysDocumentNumService.incrementLastSerialByDocumentId(Const.DOCUMENT_ID.PURCHASE_NOTICE_DOCUMENT);
        ValidatorUtils.validateEntity(scmPurchaseDto);
        scmPurchaseDto.setAuditStatus(Const.AUDIT_STATUS_WAIT);
        scmPurchaseDto.setDoClose(0);
        scmPurchaseNoticeService.saveOrUpdate(scmPurchaseDto);
        List<ScmPurchaseNoticeItem> itemList = scmPurchaseDto.getItemList();
        itemList.forEach(item -> item.setPurchaseNoticeId(scmPurchaseDto.getId()));
        if (ObjectUtil.isNotEmpty(scmPurchaseDto.getItemList())){
            scmPurchaseNoticeItemService.saveOrUpdateBatch(scmPurchaseDto.getItemList());
        }
        return Response.succeed();
    }

    /**
     * 保存收料通知
     */
    @PostMapping("/approvedIn")
    @Transactional(rollbackFor = Exception.class)
    public Response<?> approvedIn(@RequestBody ScmPurchaseNotice scmPurchaseDto) {
        // 参数校验
        if (ObjectUtil.isNotEmpty(scmPurchaseDto.getId())){
            ScmPurchaseNotice noticeDO = scmPurchaseNoticeService.getById(scmPurchaseDto.getId());
            if (noticeDO.getAuditStatus().equals(Const.AUDIT_STATUS_NORMAL)){
                Response.fail("该单据已被审核，不能编辑！");
            }
        }
        // 更新计划单号
        sysDocumentNumService.incrementLastSerialByDocumentId(Const.DOCUMENT_ID.PURCHASE_NOTICE_DOCUMENT);
        ValidatorUtils.validateEntity(scmPurchaseDto);
        scmPurchaseDto.setAuditStatus(Const.AUDIT_STATUS_NORMAL);
        scmPurchaseDto.setDoClose(0);
        scmPurchaseNoticeService.saveOrUpdate(scmPurchaseDto);
        List<ScmPurchaseNoticeItem> itemList = scmPurchaseDto.getItemList();
        itemList.forEach(item -> item.setPurchaseNoticeId(scmPurchaseDto.getId()));
        if (ObjectUtil.isNotEmpty(scmPurchaseDto.getItemList())){
            scmPurchaseNoticeItemService.saveOrUpdateBatch(scmPurchaseDto.getItemList());
        }
        return Response.succeed();
    }

    /**
     * 审核
     */
    @PostMapping("/approved")
    public Response<?> approved(@ApiParam(value = "ids") @RequestBody List<Integer> ids) {
        List<ScmPurchaseNotice> noticeList = scmPurchaseNoticeService.list(new LambdaQueryWrapper<ScmPurchaseNotice>().in(ScmPurchaseNotice::getId, ids));
        List<ScmPurchaseNotice> errors = noticeList.stream().filter(item -> item.getAuditStatus().equals(Const.AUDIT_STATUS_NORMAL)).collect(Collectors.toList());
        if (ObjectUtil.isNotEmpty(errors)){
            return Response.fail("存在已被审核单据！");
        }
        noticeList.forEach(item ->{
            item.setAuditStatus(Const.AUDIT_STATUS_NORMAL);
            item.setAuditId(TokenUtil.getUserId());
            item.setAuditTime(new Date());
        });
        scmPurchaseNoticeService.saveOrUpdateBatch(noticeList);
        return Response.succeed();
    }

    /**
     * 反审核
     */
    @PostMapping("/disApproved")
    public Response<?> disApproved(@ApiParam(value = "ids") @RequestBody List<Integer> ids) {
        List<ScmPurchaseNotice> noticeList = scmPurchaseNoticeService.list(new LambdaQueryWrapper<ScmPurchaseNotice>().in(ScmPurchaseNotice::getId, ids));
        List<ScmPurchaseNotice> errors = noticeList.stream().filter(item -> item.getAuditStatus().equals(Const.AUDIT_STATUS_WAIT)).collect(Collectors.toList());
        if (ObjectUtil.isNotEmpty(errors)){
            return Response.fail("存在未被审核单据！");
        }
        noticeList.forEach(item ->{
            item.setAuditStatus(Const.AUDIT_STATUS_WAIT);
        });
        scmPurchaseNoticeService.saveOrUpdateBatch(noticeList);
        return Response.succeed();
    }

    /**
     * 删除
     */
    @PostMapping("/del")
    public Response<?> del(@RequestBody List<Long> ids) {
        List<ScmPurchaseNotice> purchasePlansOfStaging = scmPurchaseNoticeService.list(new LambdaQueryWrapper<ScmPurchaseNotice>()
                .in(ScmPurchaseNotice::getId, ids).eq(ScmPurchaseNotice::getAuditStatus,1));
        if (ObjectUtil.isNotEmpty(purchasePlansOfStaging)){
            return Response.fail("不能删除已审核状态单据，操作失败！");
        }
        scmPurchaseNoticeService.removeByIds(ids);
        return Response.succeed();
    }

    /**
     * 分页
     */
    @PostMapping("/pageList")
    public Response<?> pageList(@RequestBody ScmPurchaseNoticePageParam scmPurchasePageParam) {
        return scmPurchaseNoticeService.findPageListByParam(scmPurchasePageParam);
    }

    /**
     * 获取详情
     */
    @GetMapping("/detail")
        public Response<?> detail(@RequestParam(value = "id", required = true) Integer id) {
        return scmPurchaseNoticeService.getNotice(id);
    }


    /**
     * 采购申请单分页列表(导出)
     */
    @PostMapping("/export")
    public Response<?> export(@Valid @RequestBody ScmPurchaseNoticePageParam scmPurchasePageParam, HttpServletResponse response) throws Exception {
        List<ScmPurchaseNoticePageVo> listByParam = scmPurchaseNoticeService.findListByParam(scmPurchasePageParam);
        ExcelUtils.exportByEasypoi(listByParam, ScmPurchaseNoticePageVo.class, "收获通知", "收获通知", response, "收获通知");
        return Response.succeed();
    }
}
